﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace Zj.DockerSample.Repositories.EntityFrameworkCore.Models
{
    public static class DbContextMigrationExtension
    {
        public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost,Action<TContext,IServiceProvider> action)
        where TContext:DbContext
        {
            using (var scope = webHost.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger = services.GetRequiredService<ILogger<TContext>>();
                var context = services.GetRequiredService<TContext>();
                try
                {
                    context.Database.Migrate();
                    action.Invoke(context, services);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "初始化种子数据失败");
                }
                return webHost;
            }
        }
    }
}
